package com.cloud.common.domain;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * cloud应用上下文，可用于获取用户基础信息
 *
 * @author wangjian
 * @version 1.0.0
 * @create 2020年09月29日16:17
 */
public class CloudApplicationContext {

    private static final Logger logger = LoggerFactory.getLogger(CloudApplicationContext.class);

    private static final ThreadLocal<CloudContext> THREAD_LOCAL = ThreadLocal.withInitial(CloudContext::new);

    /**
     * 单利对象
     */
    private static class ContextHolder {
        private final static CloudApplicationContext ACTION_CONTEXT = new CloudApplicationContext();
    }

    public static CloudApplicationContext getInstance() {
        return ContextHolder.ACTION_CONTEXT;
    }

    public CloudContext getContext() {
        logger.info("[CloudApplicationContext#getContext] thread:" + Thread.currentThread().getName() + " 获取上下文信息");
        return THREAD_LOCAL.get();
    }

    public void setContext(CloudContext cloudContext) {
        logger.info("[CloudApplicationContext#setContext] thread:" + Thread.currentThread().getName() + " 设置上下文信息：" + cloudContext.toString());
        THREAD_LOCAL.set(cloudContext);
    }

    /**
     * 清除当前线程内引用，防止内存泄漏
     */
    public void removeContext() {
        logger.info("[CloudApplicationContext#removeContext] thread:" + Thread.currentThread().getName() + " 清除上下文信息");
        THREAD_LOCAL.remove();
    }

}
